Ext.ns('ru.proburo.oms.order.components');

/**
 * @class ru.proburo.oms.order.SplitButton
 * @extends Ext.SplitButton
 */
ru.proburo.oms.order.SplitButton = Ext.extend(Ext.SplitButton, {
	constructor: function(config)
	{
		config = config || {};
		
		this.menuItems = [];
		this._handler  = config.handler;
		this._scope    = config.scope;
		this._menu	   = new Ext.menu.Menu({
			items: []
		});
		Ext.applyIf(config, {
			menu: this._menu
		});
		
		config.collection.on({
			'add': 	  this._onCollectionAdd,
			'remove': this._onCollectionRemove,
			scope:    this
		});
		
		ru.proburo.oms.order.SplitButton.superclass.constructor.call(this, config);
		
		this._addDefault();
	},
	
	_addDefault: function()
	{
		var action = this._menu.insert(0, {
			text: 	 'Новый заказ',
			iconCls: 'silk-table-add',
			group: 	 'orders-group',
			checked: false,
			handler: function(){
				var tab = this._scope._openOrder(this._scope._createOrder());
				this._handler.call(this._scope, tab);
			},
			scope:   this
		});
		
		this.setCurrent(action);
	},
	
	_onCollectionAdd: function(index, item, key)
	{
		if(item instanceof ru.proburo.oms.order.components.Detail && false == item.readonly)
		{
			var me 	  = this;	
			var id 	  = item.getId();
			var title = item.renderTitle();
			
			this.menuItems[id] = this.menu.insert(0, {
				text: 	 title,
				iconCls: 'silk-table',
				tooltip: item.tooltip,
				group: 	 'orders-group',
				checked: false,
				
				handler: function()
				{
					me._handler.call(me._scope, item);
					me.setCurrent(me.menuItems[id]);
				}
			});
			
			item.on('titlechange', this._onItemTitleChange, this);
			
			this.setCurrent(this.menuItems[id]);
		}
	},
	
	_onCollectionRemove: function(item, key)
	{
		var id = item.getId();
		
		if(this.menuItems[id])
		{
			this.menu.remove(this.menuItems[id]);
			
			item.un('titlechange', this._onItemTitleChange, this);
			
			this.setCurrent(this.menu.items.first());
		}
	},
	
	_onItemTitleChange: function(item, newTitle)
	{
		var id    = item.getId();
		var title = item.renderTitle(true);
		
		this.menuItems[id].setText(title);
	},
	
	setCurrent: function(action)
	{
		if(!Ext.isDefined(action.initialConfig))
		{
			return;
		}
		this.setText(action.initialConfig.text);
		this.setIconClass(action.initialConfig.iconCls);
		this.setTooltip(action.initialConfig.tooltip);
		
		this.currentAction = action;
		
		this.setHandler(action.initialConfig.handler, action.initialConfig.scope);
	}
});